/**
 * 移动端滚动性能优化工具
 */

/**
 * 为元素添加滚动性能优化样式
 * @param {HTMLElement} element - 需要优化的滚动元素
 */
export function optimizeScroll(element) {
  if (!element) return;

  const styles = {
    '-webkit-overflow-scrolling': 'touch',
    'transform': 'translateZ(0)',
    'will-change': 'transform',
    'backface-visibility': 'hidden',
    'contain': 'layout style paint'
  };

  Object.keys(styles).forEach(key => {
    element.style[key] = styles[key];
  });
}

/**
 * 被动事件监听器包装器
 * @param {HTMLElement} element - 目标元素
 * @param {string} eventName - 事件名称
 * @param {Function} handler - 事件处理函数
 * @param {boolean} passive - 是否使用被动模式，默认 true
 */
export function addPassiveEventListener(element, eventName, handler, passive = true) {
  if (!element) return;

  element.addEventListener(eventName, handler, { passive });

  // 返回移除监听器的函数
  return () => {
    element.removeEventListener(eventName, handler);
  };
}

/**
 * 防抖函数
 * @param {Function} func - 需要防抖的函数
 * @param {number} wait - 等待时间（毫秒）
 * @param {boolean} immediate - 是否立即执行
 * @returns {Function}
 */
export function debounce(func, wait = 300, immediate = false) {
  let timeout;

  return function executedFunction(...args) {
    const context = this;

    const later = () => {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    const callNow = immediate && !timeout;

    clearTimeout(timeout);
    timeout = setTimeout(later, wait);

    if (callNow) func.apply(context, args);
  };
}

/**
 * 节流函数
 * @param {Function} func - 需要节流的函数
 * @param {number} limit - 时间限制（毫秒）
 * @returns {Function}
 */
export function throttle(func, limit = 300) {
  let inThrottle;

  return function executedFunction(...args) {
    const context = this;

    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;

      setTimeout(() => {
        inThrottle = false;
      }, limit);
    }
  };
}

/**
 * 请求动画帧节流（RAF throttle）
 * 比 throttle 更适合滚动优化
 * @param {Function} func - 需要节流的函数
 * @returns {Function}
 */
export function rafThrottle(func) {
  let rafId = null;
  let lastArgs = null;

  return function throttled(...args) {
    lastArgs = args;

    if (rafId === null) {
      rafId = requestAnimationFrame(() => {
        func.apply(this, lastArgs);
        rafId = null;
      });
    }
  };
}

/**
 * 移除 Element UI/Plus 遮罩模糊效果
 * 在应用启动时调用一次即可
 */
export function removeDialogBlur() {
  const style = document.createElement('style');
  style.textContent = `
    .el-overlay,
    .el-popup-parent--hidden .el-overlay {
      backdrop-filter: none !important;
      -webkit-backdrop-filter: none !important;
    }
  `;
  document.head.appendChild(style);
}

/**
 * 检测是否为移动设备
 * @returns {boolean}
 */
export function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  );
}

/**
 * 获取设备像素比
 * @returns {number}
 */
export function getDevicePixelRatio() {
  return window.devicePixelRatio || 1;
}

/**
 * Vue 3 组合式函数：滚动性能优化
 * @returns {Object}
 */
export function useScrollOptimization() {
  const scrollRef = ref(null);

  onMounted(() => {
    if (scrollRef.value) {
      optimizeScroll(scrollRef.value);
    }
  });

  return {
    scrollRef
  };
}

/**
 * Vue 3 指令：滚动优化
 * 使用方式：v-scroll-optimize
 */
export const vScrollOptimize = {
  mounted(el) {
    optimizeScroll(el);
  }
};

/**
 * Vue 3 指令：被动事件监听
 * 使用方式：v-passive-scroll="handleScroll"
 */
export const vPassiveScroll = {
  mounted(el, binding) {
    if (typeof binding.value === 'function') {
      const handler = rafThrottle(binding.value);
      el._passiveScrollHandler = handler;
      addPassiveEventListener(el, 'scroll', handler);
    }
  },
  unmounted(el) {
    if (el._passiveScrollHandler) {
      el.removeEventListener('scroll', el._passiveScrollHandler);
      delete el._passiveScrollHandler;
    }
  }
};

/**
 * 性能监控工具
 */
export class PerformanceMonitor {
  constructor(threshold = 16.67) { // 60fps = 16.67ms per frame
    this.threshold = threshold;
    this.lastTime = performance.now();
    this.frameCount = 0;
    this.lagCount = 0;
  }

  checkFrame() {
    const now = performance.now();
    const delta = now - this.lastTime;

    this.frameCount++;

    if (delta > this.threshold) {
      this.lagCount++;
      console.warn(`帧延迟: ${delta.toFixed(2)}ms`);
    }

    this.lastTime = now;
  }

  getStats() {
    const lagPercent = (this.lagCount / this.frameCount) * 100;
    return {
      totalFrames: this.frameCount,
      lagFrames: this.lagCount,
      lagPercent: lagPercent.toFixed(2) + '%'
    };
  }

  start() {
    this.intervalId = setInterval(() => this.checkFrame(), 16);
  }

  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      console.log('性能统计:', this.getStats());
    }
  }
}

// 默认导出所有工具
export default {
  optimizeScroll,
  addPassiveEventListener,
  debounce,
  throttle,
  rafThrottle,
  removeDialogBlur,
  isMobile,
  getDevicePixelRatio,
  useScrollOptimization,
  vScrollOptimize,
  vPassiveScroll,
  PerformanceMonitor
};
